<template>
  <div style="width: 100%;height: 100%;display: flex">
    <div class="left_box">
      <div class="code_box">
        <ace-editor  style="width: 100%;height: 100%" :html-text-value="htmlStr" :ts-text-value="tsStr"></ace-editor>
      </div>
    </div>
    <div id="load4490_box">
      <div class="popup_box">
        <div class="inner_content_common">
          <el-button type="primary" @click="loadLayer('tiles')" size="small">加载3dtiles</el-button>
          <el-button type="primary" @click="loadLayer('gltf')" size="small">加载gltf</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>

import {initMap} from "@/widgets/modelExample_cesium/common/initMap";
import {loadTdtLayer, loadModelLayer, loadGltf} from "@/widgets/modelExample_cesium/common/loadLayers";
import {onMounted, ref} from "vue";
import AceEditor from "@/components/aceEditor.vue";

const cViewer = ref();
let point: any = null;
let polyline: any = null;
let polygon: any = null;

const htmlStr=ref(`<template>
  <div style="width: 100%;height: 100%;display: flex">
    <div id="load4490_box">
      <div class="popup_box">
        <div class="inner_content_common">
          <el-button type="primary" @click="loadLayer('tiles')" size="small">加载3dtiles</el-button>
          <el-button type="primary" @click="loadLayer('gltf')" size="small">加载gltf</el-button>
        </div>
      </div>
    </div>
  </div>
</template>


<script lang="ts" setup>

import {initMap} from "@/widgets/modelExample_cesium/common/initMap";
import {loadTdtLayer, loadModelLayer, loadGltf} from "@/widgets/modelExample_cesium/common/loadLayers";
import {onMounted, ref} from "vue";

//修改天地图
const toolbar = ref({})
onMounted(() => {
  cViewer.value = initMap("load4490_box")
  loadTdtLayer(cViewer.value, 'c', false);
})
//加载模型数据
const loadLayer = (type: string) => {
  if (type === "tiles") {
    loadModelLayer(
        cViewer.value,
        '/public/otherModal/building2/tileset.json',
        "md_tiles",
        {
          bLocTo: true,
          height: 6,
          offset: {
            "tx": 117.08,
            "ty": 40.23,
            "tz": 0,
            "rx": 0,
            "ry": 0,
            "rz": -90
          }
        }
    );
  } else if (type === "gltf") {
    loadGltf(
        cViewer.value,
        '/public/otherModal/bayard_station_valve_house/scene.gltf',
        [113.59, 34.74, 0],
        true
    )
  }
}
const removeAll = () => {

}
<\/script>

<style lang="scss" scoped>

#load4490_box {
  width: 60%;
  height: 100%;
}

.popup_box {
  position: fixed;
  left: calc(40% + 120px);
  width: 200px;
  top: 100px;
  height: 60px;
  z-index: 10;
}

.inner_content_common {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  width: 50%;
}
</style>
`);
const tsStr=ref(`
/**
 * 加载天地图
 * @param viewer
 * @param type
 */
const loadTdtLayer=(viewer:any,type:string,isAnHei:boolean=false)=>{
    viewer.imageryLayers.removeAll();
    const tdtKeys=[
    '18992e1edf6d198f398c38c5eee5aad9',
    '452fa1da60ebc9ea7c09702678f1fb96',
    'f50150db8ad49aec65c54db85d313a85',
    '576ab0b068f9559271b1c8cc65653384',
    'c57ca7cce19c08cf8d982bfddf581ccf',
    'f424a5e7adbe5c596ff4013c9e437ce9']
    let  num=Math.floor(Math.random()*(5-1)+1);
    let currentKeys=tdtKeys[num];
    //在线天地图影像服务地址(墨卡托投影)
    var TDT_IMG_W = "http://{s}.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0" +
        "&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
        "&style=default&format=tiles&tk=" + currentKeys;
    //在线天地图矢量地图服务(墨卡托投影)
    var TDT_VEC_W = "http://{s}.tianditu.gov.cn/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0" +
        "&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
        "&style=default&format=tiles&tk=" + currentKeys;
    //在线天地图影像中文标记服务(墨卡托投影)
    var TDT_CIA_W = "http://{s}.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0" +
        "&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
        "&style=default.jpg&tk=" + currentKeys
    //在线天地图矢量中文标记服务(墨卡托投影)
    var TDT_CVA_W = "http://{s}.tianditu.gov.cn/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0" +
        "&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
        "&style=default.jpg&tk=" +currentKeys;
    //在线天地图地形地图服务(墨卡托投影)
    var TDT_TER_W = "http://{s}.tianditu.gov.cn/ter_w/wmts?service=wmts&request=GetTile&version=1.0.0" +
        "&LAYER=ter&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
        "&style=default.jpg&tk=" + currentKeys;
    //在线天地图地形中文标记服务(墨卡托投影)
    var TDT_CTA_W = "http://{s}.tianditu.gov.cn/cta_w/wmts?service=wmts&request=GetTile&version=1.0.0" +
        "&LAYER=cta&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
        "&style=default.jpg&tk=" + currentKeys;
    let mapUrl = TDT_IMG_W;
    let labelUrl = TDT_CIA_W;
    if (type === 'c'){
        // 影像图
        mapUrl = TDT_IMG_W;
        labelUrl = TDT_CIA_W;
    } else if (type === 'w'){
        // 矢量图
        mapUrl = TDT_VEC_W;
        labelUrl = TDT_CVA_W;
    } else if (type ==='d'){
        // 地形图
        mapUrl = TDT_TER_W;
        labelUrl = TDT_CTA_W;
    }
    let Img = new  WebMapTileServiceImageryProvider({
        //调用影像中文服务
        url: mapUrl,
        //WMTS请求的层名称
        layer: "ter_w",
        //WMTS请求的样式名称
        style: "default",
        //MIME类型，用于从服务器检索图像
        format: "image/jpeg",
        //用于WMTS请求的TileMatrixSet的标识符
        tileMatrixSetID: "GoogleMapsCompatible",
        //天地图8个服务器
        subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
        minimumLevel: 0,
        maximumLevel: 18,
    })
    let images= viewer.imageryLayers.addImageryProvider(Img)
    if(isAnHei){
        //图层的色调
        images.hue=3;
        //图层对比度
        images.contrast=-1.2
    }
    // images.brightness=0.4
    //调用影像中文注记服务
    let cia = new  WebMapTileServiceImageryProvider({
        url: labelUrl,
        layer: "cta_w",
        style: "default",
        format: "tiles",
        tileMatrixSetID: "GoogleMapsCompatible",
        subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
        minimumLevel: 0,
        maximumLevel: 18,
    })
    viewer.imageryLayers.addImageryProvider(cia)
}
/**
 * 加载倾斜摄影的数据模型
 * @param viewer
 * @param url  http://ip:port/xxx/
 * @param layerCode
 * @param option  {
 *   "spaceError":16，屏幕空间错误 默认16，越小模型越精细，加载效率越低，越大模型粗，加载效率快
 *   "height":0,调整模型的高，默认0
 *   "offset":{
 *     "tx":109.xx, 中心位置 经度
 *     "ty":32.xx, 中心位置  纬度
 *     "tz":100.xx，中心位置高度
 *     "rx":32, X轴（经度）方向旋转角度（单位：度）
 *     "ry":32,Y轴（纬度）方向旋转角度（单位：度）
 *     "rz":32 Z轴（高程）方向旋转角度（单位：度）
 *   }， 模型旋转参数
 *   "bLocTo":true | false,是否加载后定位
 * }
 * @creeate zgf
 * @date 20230526
 * @desc 原先基于cesium@1.96，需要升级基于cesium@1.115
 */
  const   loadModelLayer= async (viewer: any, url: any, layerCode: string, option: any)=> {
    let {spaceError, height, offset, bLocTo} = option;
    if (!height) {
        height = 0;
    }
    if (!spaceError) {
        spaceError = 16;
    }
    const tileset = await Cesium.Cesium3DTileset.fromUrl(
        url, {
            maximumScreenSpaceError: spaceError,
            foveatedTimeDelay: 2,
            progressiveResolutionHeightFraction: 0.2,// 数值偏于0能够让初始加载变得模糊
            cullRequestsWhileMovingMultiplier: 10,// 值越小能够更快的剔除
            cullRequestsWhileMoving: true,   //优化选项。不要请求可能因为相机的移动而返回时未使用的磁贴
            cullWithChildrenBounds: true,  //优化选项。是否使用其子对象边界体积的联合来剔除瓷砖
            loadSiblings: true, // 如果为 true 则不会在已加载完模型后，自动从中心开始超清化模型
            immediatelyLoadDesiredLevelOfDetail: false,
            preloadWhenHidden: true,
            preferLeaves: true,

            //以下四参数一起使用
            skipLevelOfDetail: true,
            baseScreenSpaceError: 512,//跳过细节级别之前必须达到的屏幕空间错误
            skipScreenSpaceErrorFactor: 64,//定义要跳过的最小屏幕空间误差
            skipLevels: 2,
            //以下三参数一起使用
            dynamicScreenSpaceErrorDensity: 0.8, // 数值加大，能让周边加载变快
            dynamicScreenSpaceErrorFactor: 1, // 不知道起了什么作用没，反正放着吧先
            dynamicScreenSpaceError: true, // 根据测试，有了这个后，会在真正的全屏加载完之后才清晰化房屋
            //以下2参数一起使用
            cacheBytes: 134217728,//目标缓存量，单位字节，默认512M=536870912，现在改为128M
            maximumCacheOverflowBytes: 134217728,//超出缓存量，超出cacheBytes的缓存量
            preloadFlightDestinations: false,//视角移动过程中预加载相机最终移动的目的地的磁贴

        });
    viewer.scene.primitives.add(tileset);
    if (height && height !== 0) {
        contentFun.changeHeight(height, tileset);
    }
    if (offset) {
        contentFun.translationTiles(tileset, offset);
    }
    if (bLocTo) {
        viewer.zoomTo(tileset);
    }
    viewer.scene.requestRender();
    return tileset;
}
/**
 * 加载gltf模型数据
 * @param viewer
 * @param url
 * @param jwd
 */
const  loadGltf=(viewer:any,url:string,jwd:[number,number,number],isTracked:boolean=true)=>{
    let position=Cesium.Cartesian3.fromDegrees(jwd[0], jwd[1], jwd[2]);
    const heading = Cesium.Math.toRadians(135);
    const pitch = 0;
    const roll = 0;
    const hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
    const orientation = Cesium.Transforms.headingPitchRollQuaternion(
        position,
        hpr
    );
    const entity = viewer.entities.add({
        position:position  ,
        orientation: orientation,
        model: {
            uri: url,
            minimumPixelSize: 128,
            maximumScale: 20000,
        },
    });
    if(isTracked){
        viewer.trackedEntity = entity;
    }
}
export{
loadTdtLayer,
loadModelLayer,
loadGltf
}
`);

//修改天地图
const toolbar = ref({})
onMounted(() => {
  cViewer.value = initMap("load4490_box")
  loadTdtLayer(cViewer.value, 'c', false);
})
//加载模型数据
const loadLayer = (type: string) => {
  if (type === "tiles") {
    loadModelLayer(
        cViewer.value,
        '/public/otherModal/building2/tileset.json',
        "md_tiles",
        {
          bLocTo: true,
          height: 6,
          offset: {
            "tx": 117.08,
            "ty": 40.23,
            "tz": 0,
            "rx": 0,
            "ry": 0,
            "rz": -90
          }
        }
    );
  } else if (type === "gltf") {
    loadGltf(
        cViewer.value,
        '/public/otherModal/bayard_station_valve_house/scene.gltf',
        [113.59, 34.74, 0],
        true
    )
  }
}
const removeAll = () => {

}
</script>

<style lang="scss" scoped>
.left_box {
  width: 40%;
  height: 100%;
  display: flex;
  flex-direction: row-reverse;

  .code_box {
    margin: 10px;
    width: calc(100% - 220px);
    height: calc(100% - 20px);
    //border:1px solid #00ff00;
    background-color: #ffffff;
    color: #000;
    overflow-x: hidden;
    overflow-y: auto;
  }
}

#load4490_box {
  width: 60%;
  height: 100%;
}

.popup_box {
  position: fixed;
  left: calc(40% + 120px);
  width: 200px;
  top: 100px;
  height: 60px;
  z-index: 10;
}

.inner_content_common {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  width: 50%;
}
</style>
